<?php

namespace App\WebSocket;

use App\Storage\OnlineUser;
use App\Storage\OnlineClient;

use \swoole_server;
use \swoole_websocket_server;
use \swoole_http_request;
use \Exception;

/**
 * WebSocket Events
 * Class WebSocketEvents
 * @package App\WebSocket
 */
class WebSocketEvent
{
    /**
     *  打开连接时
     * @param swoole_websocket_server $server
     * @param swoole_http_request $request
     */
    public static function onOpen(\swoole_websocket_server $server, \swoole_http_request $request)
    {
        // TODO 自定义握手事件             
        // if (!empty($header['Authorization']) && !empty($header['name'])) {
        //     $authorization = Auth::getInstance('Basic')->auth('webClient', 'webClient');
        //     if ($authorization == $header['authorization']) {
        //         // 为网页用户分配身份
        //         OnlineUser::getInstance()->set($fd, $header['name'], $authorization);
        //     }
        // } else {
        //     // 设备请求登录时再为终端分配身份
        // }
    }

    /**
     * 连接将被关闭时
     * @param swoole_server $server
     * @param int $fd
     * @param int $reactorId
     * @throws Exception
     */
    public static function onClose(\swoole_server $server, int $fd, int $reactorId)
    {
        $info = $server->connection_info($fd);
        // 判断是否是有效连接
        if (isset($info['websocket_status']) && $info['websocket_status'] !== 0) {
            OnlineUser::getInstance()->delete($fd);
            OnlineClient::getInstance()->delete($fd);
            //     TaskManager::getInstance()->async(new BroadcastTask(['payload' => $message->__toString(), 'fromFd' => $fd]))
        }
    }
}
